package org.spiderflow.aria.executor;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.spiderflow.ExpressionEngine;
import org.spiderflow.aria.util.AriaDownloader;
import org.spiderflow.aria.util.M3u8Downloader;
import org.spiderflow.context.SpiderContext;
import org.spiderflow.executor.ShapeExecutor;
import org.spiderflow.model.Shape;
import org.spiderflow.model.SpiderNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
@Slf4j
public class AriaDownloadExecutor implements ShapeExecutor {

    @Autowired
    private ExpressionEngine engine;

    @Override
    public String supportShape() {
        return "aria";
    }

    @Override
    public Shape shape() {
        Shape shape = new Shape();
        //web界面上显示的图标
        shape.setImage("");
        //拖放至容器里时默认的节点名称
        shape.setLabel("aria");
        //模板文件名
        shape.setName("aria");
        //鼠标移动至图标上显示的名称
        shape.setTitle("aria");
        return shape;
    }


    @Override
    public void execute(SpiderNode node, SpiderContext context, Map<String, Object> variables) {
        String url = engine.execute(node.getStringJsonValue("url"), variables).toString();
        String token = engine.execute(node.getStringJsonValue("token"), variables).toString();
        String dir = engine.execute(node.getStringJsonValue("dir"), variables).toString();
        String jsonRpcUrl = engine.execute(node.getStringJsonValue("jsonRpcUrl"), variables).toString();
        String fileName = engine.execute(node.getStringJsonValue("fileName"), variables).toString();
        if (url.contains(".m3u8")) {
            try {
                M3u8Downloader m3u8Downloader = new M3u8Downloader();
                m3u8Downloader.setUrl(url);
                m3u8Downloader.setDir(dir);
                m3u8Downloader.setFileName(fileName);
                m3u8Downloader.send();
            } catch (Exception e) {
                log.error("下载出错，异常信息：{}", e);
            }
        } else {
            try {
                AriaDownloader aria2Json = new AriaDownloader();
                String result = aria2Json
                        .setUrl(url)
                        .setToken(token)
                        .setMethod(aria2Json.METHOD_ADD_URI)
                        .setDir(dir)
                        .addParam("referer", "*")
                        .send(jsonRpcUrl);
                log.info("{}:下载结果：{}", url, result);
            } catch (Exception e) {
                log.error("下载出错，异常信息：{}", e);
            }
        }
    }
}
